package com.cw.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cw.common.Constants;
import com.cw.common.R;
import com.cw.config.JwtConfig;
import com.cw.entity.User;
import com.cw.service.UserService;
import com.cw.utils.CodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;


@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 发送手机验证码
     * @param user
     * @param
     * @return
     */
    @PostMapping("sendMsg")
    public R sendMsg(@RequestBody User user) {
        log.info("获取到的手机号为：{}",user);
        //获取手机号
        String phone = user.getPhone();

        if (phone!=null){
//            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            String generateCode = CodeUtils.GenerateCode();
//            MailInfo mailInfo=new MailInfo();
//            String str = "<!DOCTYPE html><html><head><meta charset='UTF-8'></head><body><p style='font-size: 20px;font-weight:bold;'>尊敬的：【"+user.getPhone()+"】用户，您好！</p>"
//                    + "<p style='text-indent:2em; font-size: 20px;'>您本次的验证码是 "
//                    + "<span style='font-size:30px;font-weight:bold;color:red'>" +generateCode  + "</span>，1分钟之内有效，请尽快使用！</p>"
//                    + "<p style='text-align:right; padding-right: 20px;'"
//                    + "<a href='http://127.0.0.1:8080/front/page/login.html' style='font-size: 18px'点击链接跳转回登录界面</a></p>"
//                    + "<span style='font-size: 18px; float:right; margin-right: 60px;'>" + DateTime.now() + "</span></body></html>";
//
//            mailInfo.setMessage(str);
//            ArrayList<String> toMails = new ArrayList<>();
//            toMails.add(user.getEmail());
//            mailInfo.setMails(toMails);
//            MailUtils.sendMail2QQ(mailInfo);
//                保存验证码到redis中
                redisTemplate.opsForValue().set("code:"+phone,generateCode,5, TimeUnit.MINUTES);
                return R.success(generateCode);
        }

        return R.error("手机验证码发送失败");

    }

    @PostMapping("/login")
    public  R login (@RequestBody User user, HttpServletResponse response){
        //获取登录信息
        log.info("获取到的数据是：{}",user);
        String phone = user.getPhone();
        String code = user.getCode();
        Object redisCode = redisTemplate.opsForValue().get("code:"+phone);
        //比较验证码是否相同
        if ( !code.equals(redisCode)){
            return R.error("输入的验证码错误");
        }
        //核对账号是否在数据库中
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User existUser = userService.getOne(wrapper);
        HashMap<String, Object> map = new HashMap<>(16);
        // 生成令牌,将令牌写入响应头
        DateTime now = DateTime.now();
        DateTime dateTime = now.offsetNew(DateField.SECOND, 5);
        //签发时间
        map.put(JWTPayload.ISSUED_AT,now);
        //过期时间
        map.put(JWTPayload.EXPIRES_AT,dateTime);
        //生效时间
        map.put(JWTPayload.NOT_BEFORE,now);

        if (existUser == null){
            User user1 = new User();
            user1.setName("用户"+phone);
            user1.setPhone(phone);
            user1.setSex("未知");
            userService.save(user1);
            this.redisTemplate.opsForValue().set("USER:"+user1.getId(),user1);
            map.put("current_id", user1.getId());
            String token = JWTUtil.createToken(map, Constants.SECRET_KEY.getBytes(StandardCharsets.UTF_8));
            log.info("生成的token{}",token);
            response.setHeader("Authorization",token);
            redisTemplate.delete("code:"+phone);
            return R.success(user1);
        }else {
            map.put("current_id", existUser.getId());
            String token = JWTUtil.createToken(map, Constants.SECRET_KEY.getBytes(StandardCharsets.UTF_8));
            log.info("生成的token{}",token);
            response.setHeader("Authorization",token);
            this.redisTemplate.opsForValue().set("USER:"+existUser.getId(),existUser);
            redisTemplate.delete("code:"+phone);
            return R.success(existUser);
        }
    }

    /**
     * 退出功能
     * @param
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        Boolean delete = this.redisTemplate.delete("USER:" + JwtConfig.getCurrentId(request));
        log.info("{}",delete);
        return R.success("退出成功");
    }

    /**
     * 用户信息修改
     * @param user
     * @return
     */
    @PutMapping("/update")
    public R update(@RequestBody User user){

        Long id = user.getId();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(id!=null,User::getId,id);
        userService.update(user, wrapper);

//        userService.updateById(user);
        User byId = userService.getById(id);


//        return b?R.success("修改成功"):R.error("修改失败");
        return  R.success(byId);
    }
}
